<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>排班统计 - 生产过程管理系统</title>
    <link rel="stylesheet" href="../../assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="../../../css/style.css">
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
            background-color: #f7f7f7;
            color: #333;
        }

        .admin-layout {
            background-color: #f7f7f7;
        }

        .content-wrapper {
            background-color: #fff;
            border-radius: 12px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            padding: 24px;
            margin: 20px;
        }

        .content-header {
            margin-bottom: 24px;
            border-bottom: 1px solid #f0f0f0;
            padding-bottom: 16px;
        }

        #pageTitle {
            font-size: 24px;
            font-weight: 600;
            color: #333;
            margin: 0;
        }

        /* iOS风格表单 */
        .form-container {
            max-width: 600px;
            margin: 0 auto;
        }

        .form-group {
            margin-bottom: 20px;
            position: relative;
        }

        .form-label {
            font-size: 14px;
            font-weight: 500;
            color: #666;
            margin-bottom: 8px;
            display: block;
        }

        .required-field::after {
            content: "*";
            color: #dc3545;
            margin-left: 4px;
        }

        .form-control, .form-select {
            height: 44px;
            border-radius: 10px;
            border: 1px solid #e0e0e0;
            padding: 0 16px;
            font-size: 16px;
            transition: all 0.2s ease;
            width: 100%;
            background-color: #f9f9f9;
        }

        .form-control:focus, .form-select:focus {
            border-color: #28a745;
            box-shadow: 0 0 0 3px rgba(40, 167, 69, 0.1);
            background-color: #fff;
            outline: none;
        }

        /* 按钮样式 */
        .btn {
            height: 44px;
            border-radius: 10px;
            font-size: 16px;
            font-weight: 500;
            padding: 0 20px;
            transition: all 0.2s ease;
        }

        .btn-primary {
            background-color: #28a745;
            border-color: #28a745;
        }

        .btn-primary:hover {
            background-color: #218838;
            border-color: #1e7e34;
        }

        .btn-secondary {
            background-color: #f2f2f7;
            border-color: #f2f2f7;
            color: #28a745;
        }

        .btn-secondary:hover {
            background-color: #e5e5ea;
            border-color: #e5e5ea;
        }

        .btn-action {
            min-width: 120px;
        }

        /* 左侧菜单样式 */
        .submenu {
            display: none;
        }

        .menu-item.active > .submenu {
            display: block;
        }

        .menu-arrow {
            transition: transform 0.2s;
        }

        .menu-item.active > a > .menu-arrow {
            transform: rotate(90deg);
        }

        .submenu li a.active {
            color: #28a745;
            font-weight: bold;
            transform: translateY(2px);
            display: inline-block;
        }

        /* 响应式调整 */
        @media (max-width: 768px) {
            .content-wrapper {
                padding: 16px;
                margin: 10px;
            }

            .form-container {
                padding: 0;
            }
        }
        .submenu {
            display: none;
        }
        .menu-item.active > .submenu {
            display: block;
        }
        .menu-arrow {
            transition: transform 0.2s;
        }
        .menu-item.active > a > .menu-arrow {
            transform: rotate(90deg);
        }

        /* 统计页面样式 */
        .filter-container {
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 20px;
        }

        .filter-item {
            display: flex;
            align-items: center;
        }

        .filter-item label {
            margin-right: 10px;
            font-weight: bold;
        }

        .filter-item select {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            min-width: 150px;
        }

        .btn-refresh {
            padding: 8px 16px;
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .btn-refresh:hover {
            opacity: 0.9;
        }

        .statistics-container {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background-color: #fff;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            padding: 20px;
            flex: 1;
            min-width: 250px;
        }

        .stat-title {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 10px;
            color: #333;
        }

        .stat-value {
            font-size: 24px;
            font-weight: bold;
            color: var(--primary-color);
        }

        .stat-description {
            font-size: 12px;
            color: #666;
            margin-top: 5px;
        }

        /* 详细统计表格 */
        .statistics-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
            background-color: #fff;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }

        .statistics-table th, .statistics-table td {
            border: 1px solid #ddd;
            padding: 12px;
            text-align: left;
        }

        .statistics-table th {
            background-color: #f2f2f2;
            font-weight: bold;
        }

        .statistics-table tr:nth-child(even) {
            background-color: #f9f9f9;
        }

        /* 图表容器 */
        .chart-container {
            background-color: #fff;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            padding: 20px;
            margin-top: 20px;
            height: 300px;
        }
    </style>
    <script>
        // 当前年月
        let currentYear = new Date().getFullYear();
        let currentMonth = new Date().getMonth() + 1;
        let selectedDepartment = '表面处理车间'; // 默认部门

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function () {
            // 菜单折叠功能
            var menuItems = document.querySelectorAll('.menu-item > a');
            menuItems.forEach(function (item) {
                item.addEventListener('click', function (e) {
                    var parent = item.parentElement;
                    // 只允许单开一个折叠区
                    document.querySelectorAll('.menu-item').forEach(function (el) {
                        if (el !== parent) el.classList.remove('active');
                    });
                    parent.classList.toggle('active');
                    e.preventDefault();
                });
            });
            // 添加首页链接的点击事件
            document.querySelector('.menu-item:first-child > a').addEventListener('click', function (e) {
                e.preventDefault(); // 阻止默认行为
                window.location.href = '../homepage/manager_home.html'; // 跳转到管理员首页
            });

            // 默认展开人员管理菜单
            const personMenuItem = document.querySelector('.menu-item:nth-child(2)');
            if (personMenuItem) {
                personMenuItem.classList.add('active');
            }

            // 设置年份和月份选择框为当前年月
            document.getElementById('year-select').value = currentYear;
            document.getElementById('month-select').value = currentMonth;
            document.getElementById('department-select').value = selectedDepartment;

            // 绑定筛选事件
            document.getElementById('year-select').addEventListener('change', loadStatistics);
            document.getElementById('month-select').addEventListener('change', loadStatistics);
            document.getElementById('department-select').addEventListener('change', function() {
                selectedDepartment = this.value;
                loadStatistics();
            });
            document.getElementById('refresh-btn').addEventListener('click', loadStatistics);

            // 加载初始统计数据
            loadStatistics();
        });

        // 加载统计数据
        async function loadStatistics() {
            try {
                // 获取选中的年月和部门
                const year = document.getElementById('year-select').value;
                const month = document.getElementById('month-select').value;
                const department = document.getElementById('department-select').value;

                // 更新当前年月和部门
                currentYear = parseInt(year);
                currentMonth = parseInt(month);
                selectedDepartment = department;

                // 获取排班统计数据
                const response = await fetch(`http://localhost:8080/api/schedules/statistics/${year}/${month}/${department}`);
                if (!response.ok) {
                    throw new Error('获取统计数据失败');
                }

                const statistics = await response.json();

                // 显示统计数据
                displayStatistics(statistics);

                // 获取请假统计数据
                const leaveResponse = await fetch(`http://localhost:8080/api/leaves/statistics/${year}/${month}/${department}`);
                if (leaveResponse.ok) {
                    const leaveStatistics = await leaveResponse.json();
                    displayLeaveStatistics(leaveStatistics);
                }
            } catch (error) {
                console.error('加载统计数据出错:', error);
                alert('加载统计数据失败，请稍后重试');
            }
        }

        // 显示排班统计数据
        function displayStatistics(statistics) {
            // 显示总排班数
            document.getElementById('total-schedules').textContent = statistics.totalSchedules || 0;

            // 清空员工排班统计表
            const tableBody = document.getElementById('employee-stats-body');
            tableBody.innerHTML = '';

            // 获取员工排班数据
            const employeeShiftCount = statistics.employeeShiftCount || {};
            const shiftTypeCount = statistics.shiftTypeCount || {};

            // 将数据转换为数组以便排序
            const employeeData = [];
            for (const jobNumber in employeeShiftCount) {
                const shiftTypes = shiftTypeCount[jobNumber] || { '早班': 0, '中班': 0, '晚班': 0 };
                employeeData.push({
                    jobNumber: jobNumber,
                    totalShifts: employeeShiftCount[jobNumber],
                    morningShifts: shiftTypes['早班'] || 0,
                    afternoonShifts: shiftTypes['中班'] || 0,
                    nightShifts: shiftTypes['晚班'] || 0
                });
            }

            // 按总排班数降序排序
            employeeData.sort((a, b) => b.totalShifts - a.totalShifts);

            // 填充表格
            employeeData.forEach(async (data, index) => {
                const row = document.createElement('tr');

                // 尝试获取员工姓名
                let employeeName = '未知';
                try {
                    const response = await fetch(`http://localhost:8080/api/persons/search?keyword=${data.jobNumber}`);
                    if (response.ok) {
                        const persons = await response.json();
                        if (persons && persons.length > 0) {
                            employeeName = persons[0].name || '未知';
                        }
                    }
                } catch (error) {
                    console.error(`获取员工 ${data.jobNumber} 信息失败:`, error);
                }

                row.innerHTML = `
                    <td>${index + 1}</td>
                    <td>${employeeName}</td>
                    <td>${data.jobNumber}</td>
                    <td>${data.totalShifts}</td>
                    <td>${data.morningShifts}</td>
                    <td>${data.afternoonShifts}</td>
                    <td>${data.nightShifts}</td>
                `;

                tableBody.appendChild(row);
            });
        }

        // 显示请假统计数据
        function displayLeaveStatistics(statistics) {
            document.getElementById('total-leaves').textContent = statistics.totalLeaves || 0;
            document.getElementById('approved-leaves').textContent = statistics.approvedLeaves || 0;
            document.getElementById('rejected-leaves').textContent = statistics.rejectedLeaves || 0;
        }

        function logout() {
            // 添加确认提示
            if (confirm('确定要退出登录吗？')) {
                // 清除本地存储的登录信息
                localStorage.removeItem('userInfo');
                localStorage.removeItem('token');

                // 跳转到登录页面
                window.location.href = '../../login.html';
            }
        }
    </script>
</head>
<body>
<div class="admin-layout">
    <!-- 顶部导航栏 -->
    <header class="admin-header">
        <div class="header-left">
            <div class="logo">生产过程管理系统</div>
        </div>
        <div class="header-right">
            <span class="user-info">部门经理</span>
            <span class="user-name">
                    <script>
                        try {
                            const userInfo = localStorage.getItem('userInfo');
                            const user = JSON.parse(userInfo);
                            document.write(user.name || '未登录');
                        } catch (e) {
                            document.write('未登录');
                        }
                    </script>
                </span>
            <button class="logout-btn" onclick="logout()">退出</button>
        </div>
    </header>
    <!-- 左侧菜单 -->
    <aside class="admin-sidebar">
        <ul class="menu-list">
            <li class="menu-item">
                <a href="homepage/manager_home.html">
                    <span class="menu-icon">🏠</span>
                    <span class="menu-title">首页</span>
                </a>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">👥</span>
                    <span class="menu-title">人员管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../person/person_list.html">人员列表</a></li>
                    <li><a href="../person/person_edit.html">添加人员</a></li>
                    <li><a href="../person/schedule_edit.html">编辑排班表</a></li>
                    <li><a href="../person/schedule.html">查看排班表</a></li>
                    <li><a href="../person/schedule_statistics.html" class="active">班次统计</a></li>
                </ul>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">📦</span>
                    <span class="menu-title">物料管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../material/material_list.html">物料列表</a></li>
                    <li><a href="*">物料采购统计</a></li>
                </ul>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">⚙️</span>
                    <span class="menu-title">设备管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../device/device_list.html">设备列表</a></li>
                    <li><a href="*">设备报修报废统计</a></li>
                </ul>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">📝</span>
                    <span class="menu-title">产品管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../product/product_list.html">产品列表</a></li>
                    <li><a href="../product/editproduct_plan.html">编辑生产计划</a></li>
                    <li><a href="../product/viewproduct_plan.html">查看生产计划</a></li>
                </ul>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">🏢</span>
                    <span class="menu-title">供应商管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../provider/provider_list.html">供应商列表</a></li>
                </ul>
            </li>
        </ul>
    </aside>
    <!-- 主内容区域 -->
    <main class="admin-main">
        <h1>排班统计</h1>

        <!-- 筛选条件 -->
        <div class="filter-container">
            <div class="filter-item">
                <label for="year-select">年份:</label>
                <select id="year-select">
                    <option value="2023">2023年</option>
                    <option value="2024">2024年</option>
                    <option value="2025">2025年</option>
                </select>
            </div>

            <div class="filter-item">
                <label for="month-select">月份:</label>
                <select id="month-select">
                    <option value="1">1月</option>
                    <option value="2">2月</option>
                    <option value="3">3月</option>
                    <option value="4">4月</option>
                    <option value="5">5月</option>
                    <option value="6">6月</option>
                    <option value="7">7月</option>
                    <option value="8">8月</option>
                    <option value="9">9月</option>
                    <option value="10">10月</option>
                    <option value="11">11月</option>
                    <option value="12">12月</option>
                </select>
            </div>

            <div class="filter-item">
                <label for="department-select">部门:</label>
                <select id="department-select">
                    <option value="表面处理车间">表面处理车间</option>
                    <option value="锻压车间">锻压车间</option>
                    <option value="组装车间">组装车间</option>
                    <option value="质检车间">质检车间</option>
                    <option value="机加车间">机加车间</option>
                </select>
            </div>

            <button id="refresh-btn" class="btn-refresh">刷新</button>
        </div>

        <!-- 统计卡片 -->
        <div class="statistics-container">
            <div class="stat-card">
                <div class="stat-title">总排班数</div>
                <div id="total-schedules" class="stat-value">0</div>
                <div class="stat-description">本月总排班记录数</div>
            </div>

            <div class="stat-card">
                <div class="stat-title">请假总数</div>
                <div id="total-leaves" class="stat-value">0</div>
                <div class="stat-description">本月请假申请总数</div>
            </div>

            <div class="stat-card">
                <div class="stat-title">已批准请假</div>
                <div id="approved-leaves" class="stat-value">0</div>
                <div class="stat-description">本月已批准的请假数</div>
            </div>

            <div class="stat-card">
                <div class="stat-title">已拒绝请假</div>
                <div id="rejected-leaves" class="stat-value">0</div>
                <div class="stat-description">本月已拒绝的请假数</div>
            </div>
        </div>

        <!-- 员工排班统计表 -->
        <h2>员工排班详情</h2>
        <table class="statistics-table">
            <thead>
            <tr>
                <th>序号</th>
                <th>员工姓名</th>
                <th>工号</th>
                <th>总排班数</th>
                <th>早班</th>
                <th>中班</th>
                <th>晚班</th>
            </tr>
            </thead>
            <tbody id="employee-stats-body">
            <!-- 统计数据将通过JavaScript动态生成 -->
            </tbody>
        </table>
    </main>
</div>
</body>
</html>